use diesel::prelude::*;
use diesel::MysqlConnection;

use super::model::*;
use crate::database::{crud, schema::post, DbError};
use crate::{
    db_create, db_delete, db_read_by_field, db_read_count_from_offset_by_field, db_update,
};

db_create!(post, Post, NewPost, create);
db_read_by_field!(post, Post, read_by_sid, sid, String);
db_read_count_from_offset_by_field!(post, Post, read_count_from_offset_by_tid, tid, i32);
db_update!(post, NewPost, update);
db_delete!(post, delete);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        database::{
            self, establish_connection, table::category::model::NewCategory,
            table::tag::model::NewTag,
        },
        db_read, test_db_create, test_db_delete, test_db_read, test_db_update,
    };
    use diesel::Connection;

    db_read!(post, Post, read);

    fn insert_test_data(conn: &mut MysqlConnection) -> (i32, i32, i32) {
        let category_id = database::table::category::crud::create(
            conn,
            NewCategory {
                name: "CATE",
                desc: "DESC",
                cover: "COVER",
                slug: "LINK",
            },
        )
        .unwrap();
        let tag_id = database::table::tag::crud::create(
            conn,
            NewTag {
                name: "TAG1",
                desc: "DESC1",
                avatar: "AVATAR1",
                slug: "LINK1",
                cid: category_id,
            },
        )
        .unwrap();
        let post_id1 = create(
            conn,
            NewPost {
                title: "TITLE1",
                cover: "COVER1",
                tid: tag_id,
                sid: "SID1",
                tids: "".to_string(),
            },
        )
        .unwrap();
        let post_id2 = create(
            conn,
            NewPost {
                title: "TITLE2",
                cover: "COVER2",
                tid: tag_id,
                sid: "SID2",
                tids: "".to_string(),
            },
        )
        .unwrap();
        (post_id1, post_id2, tag_id)
    }

    test_db_create!();
    test_db_read!();
    test_db_update!(title, "NEW_TITLE".to_string());
    test_db_delete!();
}
